/**
 * @description: 拦截
 * @author: ls
 * @since: 2022-09-27 09:26:57 星期二
 */
import router from '@/router';
import { Session, SessionKey } from './utils/storage';
import { storeToRefs } from 'pinia';
import { userStore } from '@/stores/userStore';

// Session.clear()
let historyCount = Session.get(SessionKey.historyCount) * 1 || 0;
let routerMap = new Map();

router.beforeResolve((to, from, next) => {
  const { routerList } = storeToRefs(userStore());
  if (routerList.value.length > 0) {
    routerMap = new Map(routerList.value);
  }
  const toIndex = routerMap.get(to.name);
  const fromIndex = routerMap.get(from.name);
  if (toIndex || toIndex == 0) {
    if (!fromIndex || toIndex > fromIndex || (toIndex === 0 && fromIndex === 0)) {
      userStore().$patch({
        direction: 'forward',
      });
    } else {
      userStore().$patch({
        direction: 'reverse',
      });
    }
  } else {
    ++historyCount;
    if (['home', 'category', 'find', 'cart', 'user'].includes(to.name)) {
      historyCount = 0;
      routerMap.clear();
    }
    if (routerMap.get(to.name) === undefined) {
      routerMap.set(to.name, historyCount);
      Session.set(SessionKey.historyCount, historyCount);
    }

    // console.log(routerMap)
    let list = [];
    let temp = [...routerMap.keys()];
    temp.forEach((item) => {
      list.push([item, routerMap.get(item)]);
    });
    userStore().$patch({
      direction: 'forward',
      routerList: list,
    });
  }
  next();
});
